package com.xhy.documents_collection.controller.caption;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhy.documents_collection.annotations.OperLog;
import com.xhy.documents_collection.enums.BusinessType;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.cache.UserCache;
import com.xhy.documents_collection.entity.PO.team.Team;
import com.xhy.documents_collection.entity.PO.team.TeamUser;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.service.ExcelService;
import com.xhy.documents_collection.service.team.TeamService;
import com.xhy.documents_collection.service.team.TeamUserService;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: Xhy
 * CreateTime: 2022-11-18 09:29
 * 团队负责人的团队管理
 */

@RestController
@RequestMapping("/caption/team")
public class CTeamController {


    @Resource
    private TeamService teamService;

    @Resource
    private TeamUserService teamUserService;

    @Resource
    private UserService userService;

    @GetMapping("/list")
    @Authority("caption:team:list")
    public R list(){
        Integer uId = UserHolder.get();
        List<Team> teams = teamService.list(new QueryWrapper<Team>().eq("u_id", uId).select("id", "name"));
        return R.ok().data("data",teams);
    }
    /**
     * 团队列表
     * @param current
     * @param limit
     * @param name
     * @return
     */
    @GetMapping("/page")
    @Authority("caption:team:page")
    public R page(@RequestParam(value = "page") Long current,
                  @RequestParam(value = "limit") Long limit,
                  @RequestParam(required = false) String name
                  ){
        Integer uId = UserHolder.get();
        List<Team> teams = teamService.page(new Page<>(current, limit),
                new QueryWrapper<Team>().like(!ObjectUtils.isEmpty(name), "name", name)
                .eq("u_id",uId))
                .getRecords();
        for (Team team : teams) {
            // 填充团队人数
            team.setCount(teamUserService.count(new QueryWrapper<TeamUser>().eq("t_id",team.getId())));
            // 填充团队负责人
            team.setUserName(UserCache.get(team.getUId()));
            team.setFileSizeCapacityShow(team.getFileSizeUsed()+"/"+team.getFileSizeCapacity());
        }
        return R.ok().data("data",teams).count(teams.size());
    }

    // 添加
    @PostMapping
    @Authority("caption:team:add")
    @OperLog(title = ServiceType.TEAM,businessType = BusinessType.INSERT)
    public R add(@RequestBody @Validated Team team){

        return teamService.addTeam(team);
    }
    // 修改
    @PutMapping
    @Authority("caption:team:update")
    @OperLog(title = ServiceType.TEAM,businessType = BusinessType.UPDATE)
    public R update(@RequestBody @Validated Team team){
        return teamService.updateTeam(team);
    }

    // 删除
    @DeleteMapping("/{ids}")
    @Authority("caption:team:delete")
    @OperLog(title = ServiceType.TEAM,businessType = BusinessType.DELETE)
    public R delete(@PathVariable @NotBlank(message = "请选择删除的团队") String ids){
        return teamService.deleteTeam(ids);
    }


    /**
     * 获取团队人员信息
     * @param current
     * @param limit
     * @param userName
     * @return
     */
    @GetMapping("/user/page/{tid}")
    @Authority("caption:team:user:page")
    public R userPage(@RequestParam(value = "page") Long current,
                  @RequestParam(value = "limit") Long limit,
                  @RequestParam(required = false) String userName,
                  @RequestParam(required = false) String studentNumber,
                  @RequestParam(required = false) String email,
                  @PathVariable String tid
                      ){
        List<Integer> userIds = teamUserService.list(new QueryWrapper<TeamUser>()
                .eq("t_id", tid)
                .select("u_id"))
                .stream()
                .map(TeamUser::getUId)
                .collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(userIds)){
            // 查出用户
            Page<User> page = userService.page(new Page<>(current, limit), new QueryWrapper<User>().in("id", userIds)
                    .like(!ObjectUtils.isEmpty(userName),"name",userName)
                    .like(!ObjectUtils.isEmpty(studentNumber),"student_number",studentNumber)
                    .like(!ObjectUtils.isEmpty(email),"email",email)
                    .select("id", "name", "email","student_number","email"));
            return R.ok().data("data",page.getRecords()).count(page.getTotal());
        }
        return R.ok();
    }


    // 添加人员
    @PostMapping("/addUser/{tid}")
    @Authority("caption:team:user:add")
    @OperLog(title = ServiceType.USER,businessType = BusinessType.INSERT)
    public R addUser(@RequestBody @Validated User user, @PathVariable Integer tid){
        return teamService.addUser(user,tid);
    }

    // 删除人员
    @DeleteMapping("/deleteUser/{ids}")
    @Authority("caption:team:user:delete")
    @OperLog(title = ServiceType.USER,businessType = BusinessType.DELETE)
    public R deleteUser(@PathVariable String ids,@NotBlank(message = "请选择删除的团队") Integer teamId){
        return teamService.deleteUsers(ids,teamId);
    }

    @Resource
    private ExcelService excelService;

    /**
     * 批量添加用户
     * @param file
     * @param tId
     * @return
     * @throws IOException
     */
    @PostMapping("/batchUser/{tId}")
    @Authority("caption:team:batch:user")
    @OperLog(title = ServiceType.TEAM,businessType = BusinessType.INSERT)
    public R batchUser(MultipartFile file, @PathVariable Integer tId) throws IOException {
        excelService.read(file.getInputStream(),tId);
        return R.ok().message("添加完成");
    }


}
